package com.tianji.learning.utils;

import lombok.Data;

import javax.validation.constraints.Max;
import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author liuchun
 * @version 1.0
 * @date 2024/7/10 10:41
 */
@Data
public class DelayTask<T> implements Delayed {

    private final T data;
    //具体执行时间
    private final long deadLineNanos;

    public DelayTask(T data, Duration ttl) {
        this.data = data;
        this.deadLineNanos = System.nanoTime() + ttl.toNanos();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(0,deadLineNanos-System.nanoTime()),TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        long l = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (l > 0){
            return 1;
        }else if (l < 0){
            return -1;
        }else {
            return 0;
        }
    }
}
